package com.coder.ipc.aidl

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.Toast
import com.coder.ipc.R

class AidlActivity : AppCompatActivity() {
    val tag = "Calculate"

    private var mCalculate: ICalculate? = null
    private var isBindingSuccess = false

    private var mConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Toast.makeText(this@AidlActivity, "bind service success", Toast.LENGTH_SHORT).show()
            mCalculate = ICalculate.Stub.asInterface(service)
            isBindingSuccess = true
            Log.d(tag, "onServiceConnected-isBindingSuccess:$isBindingSuccess")
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Toast.makeText(this@AidlActivity, "unBind service success", Toast.LENGTH_SHORT).show()
            bind(findViewById(R.id.btn_bind))
            Log.d(tag, "onServiceDisconnected-isBindingSuccess:$isBindingSuccess")
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_aidl)
    }

    fun bind(view: View) {
        var intent = Intent()
        intent.action = "com.coder.ipc.aidl.action.CALCULATE_SERVICE"
        intent.`package` = packageName
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
    }

    fun unBind(view: View) {
        Log.d(tag, "unBind-isBindingSuccess:$isBindingSuccess")
        if (isBindingSuccess){
            isBindingSuccess = false
            unbindService(mConnection)
        }
    }

    fun confirm(view: View) {
        Log.d(tag, "confirm")
        val result = mCalculate?.add(2, 4)
        Toast.makeText(this, "result=$result", Toast.LENGTH_SHORT).show()
    }


}